// pages/record/record.js
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    year: '',
    month: "",
    days: [],
    firstDay: '',
    totalDays: '',
    index: '',
    result: [],
    arr: [],
    isTodayBaba: true,
    isSelectDateBaba:true,//选择日期以查看粑粑记录
    recordIsSelect: false,
    selectedRecords: [] // 存储查询结果
  },

  async inquireDatabase() {
    const res = await wx.cloud.callFunction({
      name: 'inquireDatabase',
    })
    return res.result
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
 

  },

  getBabaCount(arr, dateArr, data) {
    data.forEach(item => {
      const index = dateArr.indexOf(item)
      if (index !== -1) {
        arr[index]++
      } else {
        console.warn('err')
      }
    })
    this.setData({
      arr: arr,
    })
  },

  loadCalendar() {
    const { year, month } = this.data;
    // 获取当月的第一天是星期几
    const firstDay = new Date(year, month - 1, 1).getDay();
    // 获取当月的天数
    const totalDays = new Date(year, month, 0).getDate();
    // 创建日期数组
    let days = [];
    // 填充空白日期
    for (let i = 0; i < firstDay; i++) {
      days.push({ day: 0, count: 0 });
    }
    // 填充实际日期
    for (let i = 1; i <= totalDays; i++) {
      days.push({ day: i, isSelect: false, count: 0 });
    }
    const dateArr = [];
    for (let i = 0; i < days.length; i++) {
      if (days[i].day !== 0) {
        const monthStr = month < 10 ? `0${month}` : `${month}`;
        const dayStr = days[i].day < 10 ? `0${days[i].day}` : `${days[i].day}`;
        dateArr.push(`${year}-${monthStr}-${dayStr}`);
      }
    }
    const data = this.data.result.data.map(item => item.startTime.split(' ')[0]);
    const arr = new Array(totalDays).fill(0);
    this.getBabaCount(arr, dateArr, data);
    for (let i = 0; i < days.length; i++) {
      if (days[i].day !== 0) {
        days[i].count = arr[i - firstDay];
      }
    }
    this.setData({ firstDay, totalDays, days, arr });
  },

  changeLastMonth() {
    let month = this.data.month
    let year = this.data.year
    month = month - 1
    if (month < 1) {
      year--
      month = 12
    }
    this.setData({ year, month }, () => {
      this.loadCalendar();
    });
  },

  changeNextMonth() {
    let month = this.data.month
    let year = this.data.year
    month = month + 1
    if (month > 12) {
      year++
      month = 1
    }
    this.setData({ year, month }, () => {
      this.loadCalendar();
    });
  },

  async selectDay(e) {
    const index = e.currentTarget.dataset.index
    if (e.currentTarget.dataset.index >= this.data.firstDay) {
      const updates = this.data.days.map((item, idx) => {
        if (idx === index) {
          return { ...item, isSelect: true }; // 将点击的日期设为选中
        } else {
          return { ...item, isSelect: false }; // 其他日期设为未选中
        }
      })
      this.data.days[index].isSelect = true
      this.setData({
        days: updates
      })
    }
    const _openid = wx.getStorageSync('openid')
    const selectday=this.data.days[index].day
    const year = this.data.year
    const month = this.data.month
    const formateMonth = month < 10 ? `0${month}` : `${month}`
    const formateDay = selectday < 10 ? `0${selectday}` : `${selectday}`
    const today = `${year}-${formateMonth}-${formateDay}`
    const res = await db.collection('baba').where({
      startTime: db.RegExp({
        regexp: `^${today}`, // 匹配当天日期
        options: 'i'
      }),
      _openid: _openid
    }).get();
    console.log(res)
    if(res.data.length==0){
      this.setData({
        isTodayBaba:false,
        recordIsSelect: false, // 显示记录卡片
        isSelectDateBaba:false,
      })
    }else{
      this.setData({
        recordIsSelect: true, // 显示记录卡片
        isTodayBaba:true,
        selectedRecords: res.data, // 存储查询结果 
        isSelectDateBaba:false
      })
    }
  },

  async chenkIsTodayBaba() {
    const date = new Date()
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const formateMonth = month < 10 ? `0${month}` : `${month}`
    const formateDay = day < 10 ? `0${day}` : `${day}`
    const today = `${year}-${formateMonth}-${formateDay}`
    const res = await db.collection('baba').where({
      startTime: db.RegExp({
        regexp: `^${today}`, // 匹配当天日期
        options: 'i'
      })
    }).get();

    const days=this.data.days.filter(item=>item.isSelect)
    console.log(this.data.days,days)

    if (res.data.length == 0) {
      this.setData({
        isTodayBaba: false
      })
    } else {
      this.setData({
        isTodayBaba: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  toWeekReport(){
    wx.navigateTo({
      url: '/pages/weekReportPage/weekReportPage',
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
   // this.chenkIsTodayBaba()
    const result = wx.getStorageSync('dataBaseResult')
    if (result) {
      this.setData({
        year: new Date().getFullYear(),
        month: new Date().getMonth() + 1,
        result: result
      })
       this.loadCalendar();
    } else {
      const res = await this.inquireDatabase()
      this.setData({
        year: new Date().getFullYear(),
        month: new Date().getMonth() + 1,
        result: res
      })
       this.loadCalendar();
      wx.setStorage({
        key: 'dataBaseResult',
        data: res
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
